package org.darkforest.common.services.impl;

import org.darkforest.common.services.BonusWebChatService;
import org.darkforest.common.util.DateUtil;
import org.darkforest.dao.mapper.MemberMapper;
import org.darkforest.dao.mapper.OrderGoodsMapper;
import org.darkforest.dao.mapper.OrderMapper;
import org.darkforest.dao.mapper.PdLogMapper;
import org.darkforest.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created by pc on 2016/8/4.
 */
@Service
public class BonusWebChatServiceImpl implements BonusWebChatService {

    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private PdLogMapper pdLogMapper;
    /****
     * webchat端支付成功后进行分佣操作，记录到bdlog表
     * @param orderSn
     * 两种情况，1）有直接推荐人和间接推荐人 2）只有直接推荐人
     */
    @Override
    @Transactional
    public void payordertobpnus(String orderSn) {
        Order or = new Order();
        or.setOrderSn(Long.valueOf(orderSn));
        List<Order> list = orderMapper.findOrderInfoByCondition(or);
        for(Order order:list){
            Integer member_direct_id =0;//直接推荐人id
            Integer member_indirect_id =0; //间接推荐人id
            Member member = memberMapper.getMemberById(order.getBuyerId());
            if(member!=null){
                member_direct_id =member.getRecommendId()!=null?member.getRecommendId():0;
                Member member_direct = memberMapper.getMemberById(member.getRecommendId());  //直接推荐人
//                Member member_indirect = memberMapper.getMemberById(member_direct.getRecommendId()); //间接推荐人
                if(member_direct!=null){
                    member_indirect_id = member_direct.getRecommendId()!=null?member_direct.getRecommendId():0;
                }
            }
            List<OrderGoods>  ogs = orderGoodsMapper.findOrderGoodsListByOrderId(order.getOrderId());
            for(OrderGoods orderGoods:ogs){
                if(member_indirect_id!=0){

                  this.savepdlog(member_direct_id,orderGoods.getGoodsPayPrice().multiply(new BigDecimal(orderGoods.getGoodsNum())),orderGoods.getCommisRateSecond()!=null?orderGoods.getCommisRateSecond():0,order.getOrderId(),orderGoods.getGoodsId());
                  this.savepdlog(member_indirect_id,orderGoods.getGoodsPayPrice().multiply(new BigDecimal(orderGoods.getGoodsNum())),orderGoods.getCommisRate()!=null?orderGoods.getCommisRate():0,order.getOrderId(),orderGoods.getGoodsId());
                }else if(member_direct_id!=0){
                  this.savepdlog(member_direct_id,orderGoods.getGoodsPayPrice().multiply(new BigDecimal(orderGoods.getGoodsNum())),orderGoods.getCommisRate()!=null?orderGoods.getCommisRate():0,order.getOrderId(),orderGoods.getGoodsId());
                }
            }
        }

    }

    public void savepdlog(Integer memberId,BigDecimal goodspayprice,short rate,Integer orderId,Integer goodsId){
        if(rate !=0){
            PdLog pdLog = new PdLog();
            pdLog.setLgMemberId(memberId);
            pdLog.setLgMemberName(memberId.toString());
            pdLog.setLgType("bonus_plan");
            pdLog.setLgFreezeAmount(goodspayprice.multiply(new BigDecimal(rate)).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_DOWN));
            pdLog.setLgAddTime(Integer.parseInt(DateUtil.unixTimeStamp()));
            pdLog.setLgDesc("");
            pdLog.setLgOrderId(orderId);
            pdLog.setLgOrderGoodsId(goodsId);
            pdLogMapper.insertSelective(pdLog);
        }

    }

    /*****
     * 佣金结算
     */
    @Transactional
    public void settlebonus(){

        List<Order>  list = orderMapper.selectUnbonusOrders();
        for(Order order:list){
            PdLogSearchBean pdLog = new PdLogSearchBean();
            pdLog.setOrderId(order.getOrderId());
            pdLog.setLgType("bonus_plan");
            pdLog.setPageSwitch(false);
            List<PdLogVo> pdgs = pdLogMapper.selectByCondition(pdLog);
            for(PdLogVo pd:pdgs){
                pd.setLgId(null);
                pd.setLgType("cash_bonus");
                pd.setLgAvAmount(pd.getLgFreezeAmount());
                pd.setLgFreezeAmount(new BigDecimal(0));
                pd.setLgAddTime(Integer.parseInt(DateUtil.unixTimeStamp()));
                pdLogMapper.insertSelective(pd);
                MemberWithBLOBs member = memberMapper.selectByPrimaryKey(pd.getLgMemberId());
                member.setAvailablePredeposit(member.getAvailablePredeposit().add(pd.getLgAvAmount()));
                memberMapper.updateByPrimaryKeySelective(member);
            }
            order.setIsDept(1);
            orderMapper.updateByPrimaryKeySelective(order);
        }

    }
}
